package org.tangzhi.identity;

import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class UserService {

    private final UserRepository userRepository;

    private final PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Transactional
    public void addUser(User user) {
        userRepository.save(user);
    }

    public Optional<User> getUser(String username) {
        return this.userRepository.findById(username);
    }

    @Transactional
    public void changePassword(String username, String oldPassword, String newPassword) throws UserException {
        User user = this.authenticate(username, oldPassword);
        user.changePassword(passwordEncoder.encode(newPassword));
    }

    public User authenticate(String username, String password) throws UserException {
        Optional<User> userOptional = this.userRepository.findById(username);
        User user = userOptional.orElseThrow(() -> new UserException("The user does not exist."));
        if (passwordEncoder.matches(password, user.getPassword())) {
            throw new UserException("The old password is incorrect.");
        }
        return user;
    }

}
